package main

import (
	"database/sql"
	"fmt"
	pb "ihos/ihos"
	"log"
	"strings"
	"time"

	"google.golang.org/protobuf/types/known/timestamppb"
)

type VideoPadPhoto struct {
	id        int32 //PK
	hzid      int32
	phototype int32
	url       string
	expireat  int64
}

func (d *VideoPadPhoto) GetFromDB(id int32) error {
	sql := "SELECT id,hzid,photo_type,url,expire_at FROM videopad_photos WHERE id=$1"
	return DBConn.db.QueryRow(sql, id).Scan(&d.id, &d.hzid, &d.phototype, &d.url, &d.expireat)
}

func (w *VideoPadPhoto) Search() (pbs []*VideoPadPhoto, err error) {
	sqlStr := "SELECT id,hzid,photo_type,url,expire_at FROM videopad_photos"
	conds := []string{}
	if w.id > 0 {
		conds = append(conds, "id="+fmt.Sprint(w.id))
	}
	if w.hzid > 0 {
		conds = append(conds, "(hzid="+fmt.Sprint(w.hzid)+" OR hzid=0)")
	} else {
		conds = append(conds, "hzid=0")
	}
	if w.phototype > 0 {
		conds = append(conds, "photo_type="+fmt.Sprint(w.phototype))
	}
	conds = append(conds, "expire_at>"+fmt.Sprint(time.Now().Unix()))
	if len(conds) > 0 {
		sqlStr += " WHERE "
		sqlStr += strings.Join(conds, " AND ")
	}
	fmt.Println(sqlStr)
	var rows *sql.Rows
	if rows, err = DBConn.db.Query(sqlStr); err != nil {
		log.Println(err)
		return nil, err
	}
	defer rows.Close()
	out := make([]*VideoPadPhoto, 0)
	for rows.Next() {
		w := &VideoPadPhoto{}
		if err = rows.Scan(&w.id, &w.hzid, &w.phototype, &w.url, &w.expireat); err != nil {
			log.Println(err)
		} else {
			out = append(out, w)
		}
	}
	return out, nil
}

func (d *VideoPadPhoto) SaveToDB(id int32) error {
	sql := ""
	var err error
	if id > 0 { //update
		sql = "UPDATE videopad_photos set photo_type=$1,url=$2,expire_at=$3 where hzid=$4 RETURNING id"
		err = DBConn.db.QueryRow(sql, d.phototype, d.url, d.expireat, d.hzid).Scan(&d.id)
	} else { //insert
		sql = "INSERT INTO videopad_photos(hzid,photo_type,url,expire_at)VALUES($1,$2,$3,$4) RETURNING id"
		err = DBConn.db.QueryRow(sql, d.hzid, d.phototype, d.url, d.expireat).Scan(&d.id)
	}
	return err
}

func (w *VideoPadPhoto) toPB() *pb.VideoPadPhoto {
	p := &pb.VideoPadPhoto{
		ID:       w.id,
		HZID:     w.hzid,
		Type:     pb.VideoPadPhoto_PHOTOTYPE(w.phototype),
		URL:      w.url,
		ExpireAt: &timestamppb.Timestamp{Seconds: w.expireat},
	}
	return p
}

func (w *VideoPadPhoto) fromPB(p *pb.VideoPadPhoto) *VideoPadPhoto {
	w.id = p.GetID()
	w.hzid = p.GetHZID()
	w.phototype = int32(p.GetType())
	w.url = p.GetURL()
	w.expireat = p.GetExpireAt().Seconds
	return w
}
